package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Contacts;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息服务
 */
@Service
public class IMService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AnnouncementService announcementService;

    @Reference(version = "1.0.0")
    private UsersApi usersApi;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    /**
     * 添加好友关系
     * 需要做2件事：1、保存数据到MongoDB，2、好友关系注册到环信
     */
    public Boolean contactUser(Long friendId) {
        //需要做2件事，1、保存数据到MongoDB，2、好友关系注册到环信
        Users users = new Users();
        users.setUserId(UserThreadLocal.get().getId());
        users.setFriendId(friendId);

        // 1、保存数据到MongoDB
        this.usersApi.saveUsers(users);

        // 2、好友关系注册到环信
        String url = ssoUrl + "user/huanxin/contacts/" + users.getUserId() + "/" + users.getFriendId();
        ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(url, null, Void.class);

        return responseEntity.getStatusCodeValue() == 200 ? true : false;
    }

    public PageResult queryContactsList(Integer page, Integer pagesize, String keyword) {
        PageInfo<Users> pageInfo = this.usersApi.queryUsersList(UserThreadLocal.get().getId(), page, pagesize);
        List<Users> usersList = pageInfo.getRecords();

        List<Contacts> contactsList = new ArrayList<>();
        //查询用户（好友）的信息
        for (Users users : usersList) {
            UserInfo userInfo = userInfoService.queryUserInfoById(users.getFriendId());

            Contacts contacts = new Contacts();

            contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            contacts.setUserId(userInfo.getUserId().toString());
            contacts.setNickname(userInfo.getNickName());
            contacts.setGender(userInfo.getSex().name().toLowerCase());
            contacts.setAvatar(userInfo.getLogo());
            contacts.setAge(userInfo.getAge());

            contactsList.add(contacts);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pagesize);
        pageResult.setPage(page);
        pageResult.setItems(contactsList);

        return pageResult;
    }

    public PageResult queryMessageLikeList(Integer page, Integer pagesize) {
        return this.messageCommentList(1, page, pagesize);
    }

    public PageResult queryMessageCommentList(Integer page, Integer size) {
        return this.messageCommentList(2, page, size);
    }

    public PageResult queryMessageLoveList(Integer page, Integer size) {
        return this.messageCommentList(3, page, size);
    }

    private PageResult messageCommentList(Integer type, Integer page, Integer size) {
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(UserThreadLocal.get().getId(), type, page, size);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(size);

        List<Comment> records = pageInfo.getRecords();

        List<MessageLike> messageLikeList = new ArrayList<>();
        for (Comment record : records) {
            UserInfo userInfo = this.userInfoService.queryUserInfoById(record.getUserId());
            MessageLike messageLike = new MessageLike();
            messageLike.setId(record.getId().toHexString());
            messageLike.setAvatar(userInfo.getLogo());
            messageLike.setNickname(userInfo.getNickName());
            messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));
            messageLikeList.add(messageLike);
        }

        pageResult.setItems(messageLikeList);
        return pageResult;
    }

    public PageResult queryMessageAnnouncementList(Integer page, Integer size) {
        IPage<Announcement> announcementPage = this.announcementService.queryList(page, size);

        List<MessageAnnouncement> list = new ArrayList<>();

        for (Announcement record : announcementPage.getRecords()) {
            MessageAnnouncement ma = new MessageAnnouncement();
            ma.setId(record.getId().toString());
            ma.setTitle(record.getTitle());
            ma.setDescription(record.getDescription());
            ma.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));
            list.add(ma);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(size);
        pageResult.setItems(list);

        return pageResult;
    }
}
